package com.shanghaionstar.user;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.more.response.PrepaidCardResponse;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.ActivateType;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.user.iview.IPayCardView;
import com.shanghaionstar.user.presenter.PayCardOthetActivePresenter;
import com.shanghaionstar.user.presenter.PayCardPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.weight.TopLayout;

/**
 * Created by Mengzhou Gu on 2016/7/29.
 */
//OwnerCheckCardfragment
public class PayCardFragment extends BaseFragment implements IPayCardView, View.OnFocusChangeListener {
    @FindViewById(R.id.tv_name)
    TextView tv_name;
    @FindViewById
    private CircleImageView head_iv;
    private String vin;
    @FindViewById
    private TopLayout top_layout = null;
    @FindViewById
    // 切换车辆// 车辆品牌// 车架号// 为其他人激活// 历史激活记录
//    tv_history_active = null,
    private TextView tv_qiehuan_car = null, tv_car_brand = null, tv_vin_number = null, tv_other_active = null, tv_phone_number,
           tv_card_number_error;
    @FindViewById
    private DeleteEditText et_carnumber_value = null, et_password_value;
//    @FindViewById(background = R.drawable.user_cardpay_head)
//    private ImageView iv_qiehuan_icon;// 切换车辆icon
    @FindViewById(background = R.drawable.onstar_join_me_bg)
    private RelativeLayout layout_background;
    @FindViewById(background = R.drawable.user_paycard_line_one)
    private CustomImageView iv_line, line_belew;
    @FindViewById
    private LinearLayout layout_info = null;
    @FindViewById
    private Button option_home_btn;

    private PrePayActivity parentActivity;

    private Bundle bundle;
    private OnstarApplication myApp;
    private Vehicle current_vehicleInfo;
    public static boolean backFromActiveHis = false;
    private PayCardPresenter presenter;
    private ProgressDialog dialog;
    @FindViewById
    private TextView right_btn_text;
    @FindViewById
    private ImageButton right_btn;

    @Override
    public int getLayoutId() {
        return R.layout.user_paycard_fragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bundle = getArguments();
        //为他人激活去掉为他人激活view yongqiang tao
        if (bundle != null) {
            tv_other_active.setVisibility(View.GONE);
        }
        parentActivity = (PrePayActivity) getActivity();
        presenter = new PayCardPresenter(parentActivity.getScheduler(), this.parentActivity, et_carnumber_value, et_password_value, bundle);
        presenter.setView(this);
        //为他人激活从EditText输入 CarRecognitionfragment传来的vin
       /* if (bundle != null) {
        }*/
        // option_home_btn.setText(R.string.next_step);
        right_btn_text.setText(getResources().getString(R.string.next_step));
        myApp = (OnstarApplication) getActivity().getApplicationContext();
       /* String imageUrl = ShareUtils.getString("imageUrl", parentActivity);
        initView(imageUrl);*/
        if (!CommonUtil.isNull(myApp.getHeadImgRes())) {
            initView(myApp.getHeadImgRes().getFullUrl());
        }
        if (ApplicationUtil.getInstance().getCurrentVehicle() != null) {
            current_vehicleInfo = ApplicationUtil.getInstance().getCurrentVehicle();
            tv_car_brand.setText(current_vehicleInfo.getMakeDesc() + current_vehicleInfo.getModelDesc());
            String vin = current_vehicleInfo.getVin();

            tv_vin_number.setText(CommonUtil.maskWithAllStar(vin, 3, 4));
            if (ApplicationUtil.getInstance().getMobile() != null) {
                String mobile = ApplicationUtil.getInstance().getMobile();
                tv_phone_number.setText(CommonUtil.maskWithStar(mobile, 3, 4));
            } else {
                String emial = ApplicationUtil.getInstance().getEmail();
                tv_phone_number.setText(CommonUtil.maskWithStar(emial, 3, 4));
            }
            tv_name.setText(ApplicationUtil.getInstance().getLastName() + "" + getString(R.string.xx));
        }
        et_carnumber_value.setOnFocusChangeListener(this);
        et_password_value.setOnFocusChangeListener(this);
 /*       top_layout.setLeftButtonClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                CommonUtil.hideKeyBoard(onActivity(), et_password_value);
                CommonUtil.hideKeyBoard(getActivity(), et_password_value);
                back();
            }
        });
*/
        top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtil.hideKeyBoard(getActivity(), et_password_value);
                //  back();
                BusinessUtil.sendReportByClickType(getActivity(),FunctionNameFindId.Prepaidcardactive_back.getStringValue());
                parentActivity.finish();
            }
        });
/*
        top_layout.setOnRightClickListener(getResources().getString(R.string.history_recoder), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PayCardFragment.this.parentActivity.hideSoftInput();
                BusinessUtil.sendReportByClickType(onActivity(), FunctionNameFindId.PreSaleActivateOrderHistory.getStringValue());
                BusinessUtil.updateConfigValue(FinalConfigParams.OWNER_JUMP, "true", onActivity());
                ActiviteHistoryFragment historyfragment = new ActiviteHistoryFragment();
                changeFragment(parentActivity.fragmentManager, historyfragment, ActiviteHistoryFragment.class.getName());
            }
        });*/

//        top_layout.setRightTextBg(R.drawable.onstar_personal_btn);
      /*  right_btn.setImageResource(R.drawable.onstar_personal_btn);
        top_layout.setRightTextBg(Color.TRANSPARENT);*/
        top_layout.setOnRightTextClickLstener(getResources().getString(R.string.history_recoder), new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                PayCardFragment.this.parentActivity.hideSoftInput();
                BusinessUtil.sendReportByClickType(onActivity(), FunctionNameFindId.PreSaleActivateOrderHistory.getStringValue());
//                BusinessUtil.updateConfigValue(FinalConfigParams.OWNER_JUMP, "true", onActivity());
                PreferencesUtls.getInstance(onActivity()).putBoolean(FinalConfigParams.OWNER_JUMP,true);
                ActiviteHistoryFragment historyfragment = new ActiviteHistoryFragment();
                changeFragment(parentActivity.fragmentManager, historyfragment, ActiviteHistoryFragment.class.getName());
            }
        });
//       right_btn_text.setTextColor(Color.WHITE);
    }

    private void initView(String url) {
        DisplayImageOptions options = OnstarApplication.getOptions(false, R.drawable.def_login_head);
        if (url != null) {
            ImageLoader.getInstance().displayImage(url, head_iv, options);
        }
    }

/*
    private void showHeadImage(HeadImgRes headImgRes) {
        DisplayImageOptions options = OnstarApplication.getOptions(false, R.drawable.def_login_head);
        if (headImgRes != null && !CommonUtil.isNull(headImgRes.getFullUrl())) {
            ImageLoader.getInstance().displayImage(headImgRes.getFullUrl(), head_iv, options);
        }

    }*/


    public void changeFragment(FragmentManager fragmentManager, ActiviteHistoryFragment fragment, String tag) {
        if (null != fragmentManager.findFragmentByTag(tag))
            return;
        FragmentTransaction p_FragmentTransaction = fragmentManager.beginTransaction();
        p_FragmentTransaction.replace(R.id.fragment_container, fragment, tag);
        p_FragmentTransaction.addToBackStack(null);
        p_FragmentTransaction.commitAllowingStateLoss();
    }


/*
    */

    /**
     * @param @param  cardnumber
     * @param @param  password
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: checkCardAndPassword
     * @Description: 检验卡号和密码格式是否正确
     *//*

    private boolean checkCardAndPassword(EditText cardnumber, EditText password) {
        if (CommonUtil.isNull(cardnumber.getText().toString())) {
            return false;
        }
        if (CommonUtil.isNull(password.getText().toString())) {
            return false;
        }

        return true;
    }
*/

/*
    public boolean checkDataPPC(String ppcCardNum) {
        String card = ppcCardNum.trim();
        if (card.startsWith("D")) {
            if (ApplicationUtil.getInstance().getCurrentVehicle() {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
*/
    @OnClick({R.id.tv_other_active, R.id.activate_button})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activate_button:  //立即激活
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Prepaidcardactive_activenow.getStringValue());
                CommonUtil.hideKeyBoard(getActivity(), et_password_value);
                layout_info.setFocusable(true);
                layout_info.setFocusableInTouchMode(true);
                layout_info.requestFocus();
                // 校验格式,发送请求
                if (presenter.checkCardAndPassword(et_carnumber_value, et_password_value)) {
                    if (et_carnumber_value.getText().toString().length() != 10) {
                        tv_card_number_error.setVisibility(View.VISIBLE);
                        tv_card_number_error.setText(getString(R.string.SB027_MSG001));
                        return;
                    }
                    if (!presenter.checkDataPPC(et_carnumber_value.getText().toString())) {
                        tv_card_number_error.setVisibility(View.VISIBLE);
                        tv_card_number_error.setText(getString(R.string.SB027_MSG022));
                        return;
                    }
                    // 显示进度条
                    dialog = showLoadProgress();
                    dialog.setCancelable(false);
                    dialog.show();

                    presenter.getData();


                } else {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setCode("SB027_MSG004");
                    ErrorCodeUtil.ShowErrorSompMsg(getActivity(), errorInfo);
                }
                break;
            case R.id.tv_other_active:  //为他人激活
                BusinessUtil.updateConfigValue(FinalConfigParams.OTHERS_ACTIVITY, "true", getActivity());
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.PreSaleForOtherPerson.getStringValue());
                //			CommonUtil.operateB2CReport(FunctionNameFindId.PPC_another_button.getStringValue(), getActivity());
                PayCardOtherActiveFragment carRecognifragment = new PayCardOtherActiveFragment();
                //      changeFragment(parentActivity.fragmentManager, carRecognifragment, PayCardOtherActiveFragment.class.getName());
                parentActivity.changeFragment(parentActivity.fragmentManager, carRecognifragment, PayCardOtherActiveFragment.class, true);

                break;
            default:
                break;

        }
    }

    @Override
    public void onResume() {
        BusinessUtil.updateConfigValue(FinalConfigParams.OTHERS_ACTIVITY, "false", getActivity());
        parentActivity.current_fragment = "PayCardFragment";
        if (backFromActiveHis) {
            et_carnumber_value.setText("");
            et_password_value.setText("");
            backFromActiveHis = false;
        }
        super.onResume();
        if (myApp.getHeadImgRes() != null && myApp.getHeadImgRes() != null && !CommonUtil.isNull(myApp.getHeadImgRes().getFullUrl()))
            initView(myApp.getHeadImgRes().getFullUrl());
    }

    @Override
    public void setLoading(boolean isLoading) {
        if (dialog != null) {
            if (isLoading) {
                if (!dialog.isShowing())
                    dialog.show();
            } else {
                if (dialog.isShowing())
                    dialog.dismiss();
            }
        }
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onReponseSuccess(PrepaidCardResponse prepaidCardResponse) {

    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }


    @Override
    public void showSuccess(PrepaidCardResponse prepaidCardResponse) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("obj", prepaidCardResponse);
        bundle.putString("card_number", et_carnumber_value.getText().toString().trim());
        bundle.putString("card_password", et_password_value.getText().toString().trim());
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getCurrentVehicle())) {
            bundle.putString("vin", ApplicationUtil.getInstance().getCurrentVehicle().getVin());
            bundle.putString("model", ApplicationUtil.getInstance().getCurrentVehicle().getModel());
            bundle.putString("make", ApplicationUtil.getInstance().getCurrentVehicle().getMake());
        }
//        BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.PPC_validate_button.getStringValue());
        PayCardDetailFragment activedetailfragment = new PayCardDetailFragment();
        bundle.putSerializable("activateType", ActivateType.Subscriber);
        activedetailfragment.setArguments(bundle);
        if (activedetailfragment != null) {
            //                        activedetailfragment.activatePrepaidCard();//调用预付卡激活函数
        }
        parentActivity.changeFragment(parentActivity.fragmentManager, activedetailfragment, PayCardDetailFragment.class, true);

    }

    @Override
    public void showFailure(Bundle bundle) {
        ErrorInfo errorInfo2 = new ErrorInfo();
        errorInfo2.setCode(ErrorEnum.SB027_MSG007.getStringValue());
        ErrorCodeUtil.ShowErrorSompMsg(getActivity(), errorInfo2);
    }

    @Override
    public void showError(Bundle bundle, Exception e) {
//        dismissDialog(dialog);
//        AlertDialogUtil.showDialogByExceptionCode(parentActivity, (HttpException) e);
//
//        ErrorInfo errorInfo = (ErrorInfo) bundle.getSerializable("errorInfo");
//
//        ErrorCodeUtil.ShowErrorSompMsg(getActivity(), errorInfo);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        et_password_value.onDestory();
        et_carnumber_value.onDestory();
        top_layout = null;
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_carnumber_value:
                if (!hasFocus) {
                    // 格式校验
                    if (!et_carnumber_value.getText().toString().trim().equals("")
                            && et_carnumber_value.getText().toString().length() != 10) {

                        tv_card_number_error.setVisibility(View.VISIBLE);
                        tv_card_number_error.setText(getString(R.string.SB027_MSG001));
                    }
                    if (!presenter.checkDataPPC(et_carnumber_value.getText().toString())) {
                        tv_card_number_error.setVisibility(View.VISIBLE);
                        tv_card_number_error.setText(getString(R.string.SB027_MSG022));
                        return;
                    }
                } else {
                    BusinessUtil.sendReportByClickType(getActivity(),FunctionNameFindId.Prepaidcardactive_inputcardNo.getStringValue());
                    tv_card_number_error.setVisibility(View.GONE);
                }
                break;
            case R.id.et_password_value:
                if(hasFocus) {
                    BusinessUtil.sendReportByClickType(getActivity(),FunctionNameFindId.Prepaidcardactive_inputcardpw.getStringValue());

                }
                break;
            default:
                break;
        }
        DeleteEditText clearText = (DeleteEditText) v;
        clearText.hasFocus(hasFocus);
        if (hasFocus) {
            clearText.setDeleteIconVisible(clearText.getText().length() > 0);
        } else {
            clearText.setDeleteIconVisible(false);
        }
    }

    @Override
    public void onFragmentBackPress() {
//        super.onFragmentBackPress();
//        back();
        BusinessUtil.sendReportByClickType(getActivity(),FunctionNameFindId.Prepaidcardactive_back.getStringValue());
        parentActivity.finish();
    }
}
